package com.googlecode.yoohoo.io.socket;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class XmppDecoder extends CumulativeProtocolDecoder {
	private static final String KEY_XMPP_XML_PARSER = "yoohoo.xmpp.xml.parser";
	
	@Override
	protected boolean doDecode(IoSession session, ByteBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		IXmppXmlParser xmlParser = (IXmppXmlParser)session.getAttribute(KEY_XMPP_XML_PARSER);
		if (xmlParser == null) {
			xmlParser = new DefaultXmppXmlParser();
			session.setAttribute(KEY_XMPP_XML_PARSER, xmlParser);
		}
		
		String[] messages = xmlParser.parse(in);
		if (messages != null) {
			for (String message : messages) {
				out.write(message);
			}
		}
		
		return !in.hasRemaining();
	}

}
